package com.rem.elasticsearch.apidemo.doc;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;

import java.io.IOException;
import java.util.Iterator;

import static org.apache.http.HttpHost.DEFAULT_SCHEME_NAME;

/**
 * 查询单个/多个索引的所有文档
 *
 * @author Rem
 * @date 2021-05-30
 */

public class DocSearch {

    public static void main(String[] args) throws IOException {
        // 创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, DEFAULT_SCHEME_NAME)));
        // 查询文档 - 请求对象
        SearchRequest request = new SearchRequest();
        // 设置索引及唯一性标识  可多填
        request.indices("user");

        SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);

        //3.打印结果信息
        SearchHits hits = response.getHits();

//        for (SearchHit hit : hits) {
//            System.err.println(hit);
//        }

//        SearchHit[] hits1 = hits.getHits();
//        for (SearchHit documentFields : hits1) {
//            System.err.println(documentFields.getSourceAsString());
//        }


        Iterator<SearchHit> iterator = hits.iterator();
        while (iterator.hasNext()) {
            SearchHit hit = iterator.next();
            System.err.println(hit.getSourceAsString());
        }

        System.out.println("耗时：" + response.getTook());
        System.out.println("_result:" + response.toString());

        // 关闭ES客户端
        esClient.close();
    }
}
